package com.antwei.dppx;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

public class MainActivity extends Activity {

	private EditText etPxIn;
	private EditText etDpOut;
	private EditText etDpIn;
	private EditText etPxOut;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub

		etPxIn = (EditText) findViewById(R.id.et_pxin);
		etDpOut = (EditText) findViewById(R.id.et_dpout);
		etDpIn = (EditText) findViewById(R.id.et_dpin);
		etPxOut = (EditText) findViewById(R.id.et_pxout);

		etPxIn.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String pxStr = etPxIn.getText().toString();
				if (!pxStr.equals("") && pxStr != null) {

					float px = Float.valueOf(pxStr);
					etDpOut.setText(px2dp(px) + "");
				}

			}
		});

		etDpIn.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				String dpStr = etDpIn.getText().toString();
				if (!dpStr.equals("") && dpStr != null) {

					float dp = Float.valueOf(etDpIn.getText().toString());
					etPxOut.setText(dp2px(dp) + "");
				}

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private float dp2px(float dpValue) {
		float scale = getResources().getDisplayMetrics().density;
		return dpValue * scale;
	}

	private float px2dp(float pxValue) {
		float scale = getResources().getDisplayMetrics().density;
		return pxValue / scale ;
	}
}
